//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { Button, ConfigProvider, Space, Tabs } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
import { createRoot } from 'react-dom/client';
import { BrowserRouter, useLocation } from "react-router-dom";
import { listen } from '@tauri-apps/api/event';
import type * as NoticeType from '@/api/notice_type';
import { BookOutlined, CloseSquareOutlined, ProjectOutlined, PushpinFilled, PushpinOutlined, UserOutlined } from "@ant-design/icons";
import { appWindow } from "@tauri-apps/api/window";
import '@/styles/global.less';
import UserTodoList from "./UserTodoList";
import IssueTodoList from "./IssueTodoList";
import { type USER_TYPE, USER_TYPE_INTERNAL } from "@/api/user";
import GitTodoList from "./GitTodoList";


const UserTodoApp = () => {
    const location = useLocation();
    const urlParams = new URLSearchParams(location.search);
    const userFlag = (urlParams.get("userFlag") ?? "false").toLowerCase();
    const issueFlag = (urlParams.get("issueFlag") ?? "false").toLocaleLowerCase();
    const userType = parseInt(urlParams.get("userType") ?? "0") as USER_TYPE;
    const userToken = urlParams.get("userToken") ?? "";

    const [userTab, setUserTab] = useState(userFlag.startsWith("t"));
    const [issueTab, setIssueTab] = useState(issueFlag.startsWith("t"));
    const [onTop, setOnTop] = useState(true);
    const [activeKey, setActiveKey] = useState("");

    useEffect(() => {
        const tmpList = [] as string[];
        if (userType != USER_TYPE_INTERNAL) {
            tmpList.push("git");
        }
        if (userTab) {
            tmpList.push("user");
        }
        if (issueTab) {
            tmpList.push("issue");
        }
        if (tmpList.includes(activeKey)) {
            return;
        }
        if (tmpList.length > 0) {
            setActiveKey(tmpList[0]);
        }
    }, [userTab, issueTab]);

    useEffect(() => {
        const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
            const notice = ev.payload;
            if (notice.ClientNotice?.TodoConfigChangeNotice != undefined) {
                setUserTab(notice.ClientNotice.TodoConfigChangeNotice.userFlag);
                setIssueTab(notice.ClientNotice.TodoConfigChangeNotice.issueFlag);
            }
        });
        return () => {
            unListenFn.then((unListen) => unListen());
        };
    }, []);

    return (
        <div style={{
            background: "rgba(248, 248, 248, 0.8)",
            width: "100wh",
            height: "100vh",
            cursor: "move",
            border: "2px solid #aaa",
            borderRadius: "10px"
        }} data-tauri-drag-region>
            <div style={{ position: "relative", height: "30px", paddingTop: "10px" }} data-tauri-drag-region>
                <div style={{ position: "absolute", left: "10px", fontSize: "16px", fontWeight: 600 }}>当前待办</div>
                <Space style={{ position: "absolute", right: "20px" }}>
                    <Button type="text" icon={onTop ? <PushpinFilled style={{ fontSize: "24px" }} title='取消置顶' /> : <PushpinOutlined style={{ fontSize: "24px" }} title='置顶' />} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        if (onTop) {
                            appWindow.setAlwaysOnTop(false).then(() => setOnTop(false));
                        } else {
                            appWindow.setAlwaysOnTop(true).then(() => setOnTop(true));
                        }
                    }} />
                    <Button type="text" icon={<CloseSquareOutlined style={{ fontSize: "24px" }} title="关闭" />} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        appWindow.close();
                    }} />
                </Space>
            </div>
            <Tabs tabPosition="bottom" style={{ height: "calc(100vh - 50px)", marginTop: "20px", cursor: "default" }}
                tabBarStyle={{ fontWeight: 700, marginLeft: "20px" }}
                activeKey={activeKey} onChange={key => setActiveKey(key)}>
                {userType != USER_TYPE_INTERNAL && userToken != "" && (
                    <Tabs.TabPane key="git" tab={<Space size="small" style={{ fontSize: "16px" }}><BookOutlined />Git待办</Space>}>
                        {activeKey == "git" && (
                            <GitTodoList userType={userType} userToken={userToken} />
                        )}
                    </Tabs.TabPane>
                )}
                {userTab == true && (
                    <Tabs.TabPane key="user" tab={<Space size="small" style={{ fontSize: "16px" }}><UserOutlined />个人待办</Space>} >
                        {activeKey == "user" && (
                            <UserTodoList />
                        )}
                    </Tabs.TabPane>
                )}
                {issueTab == true && (
                    <Tabs.TabPane key="issue" tab={<Space size="small" style={{ fontSize: "16px" }}><ProjectOutlined />项目待办</Space>}>
                        {activeKey == "issue" && (
                            <IssueTodoList />
                        )}
                    </Tabs.TabPane>
                )}
            </Tabs>
        </div>
    );
};

const App = () => {
    return (
        <ConfigProvider locale={zhCN}>
            <BrowserRouter>
                <UserTodoApp />
            </BrowserRouter>
        </ConfigProvider>
    );
}

const root = createRoot(document.getElementById('root')!);
root.render(<App />);